<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/admin.php';

/**
 * Контроллер создания и изменения торрента
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Admin_Update_Torrent extends Admin {
     
    /**
     * Идентификатор видео
     * @var int
     */
    private $idVideo = 0;
     
    /**
     * Идентификатор торрента
     *
     * @access private
     * @var integer
     */
    var $_id_torrent = 0;
     
    /**
     * Конструктор класса
     *
     * @access public
     * @return Admin_Update_Torrent
     */
    function Admin_Update_Torrent() {
        parent::Admin();
        // Выковыриваем идентификатор
        if (false !== $this->input->get('id')) {
            $this->_id_torrent = (int) $this->input->get('id');
        }
        $this->set_menu(6, 5);
        // Подгружаем модельку
        $this->load->model('m_video_torrent', 'm_torrent');
        $this->m_torrent->set_id($this->_id_torrent);
        $this->load->language('video');
        if (false !== $this->input->get('video')) {
            $this->idVideo = (int) $this->input->get('video');
        }
        $this->load->model('m_video');
        $this->m_video->set_id($this->idVideo);
        if (0 == $this->m_video->get_id('id_video')) {
            $this->redirect('admin_manage_videos');
        }
        if ($this->_id_torrent > 0 && $this->idVideo != $this->m_torrent->get('id_video')) {
            $this->redirect('admin_manage_torrents', 'index', array('video' => $this->idVideo));
        }
        $this->add_param('id_video', $this->idVideo);
        $this->add_param('video_title', $this->m_video->get('title'));
    } // end Admin_Update_Torrent
     
    /**
     * Метод по умолчанию
     *
     * @access public
     */
    function index() {
        $data = array();
        // Стандартные поля
        $title = $this->m_torrent->get('title');
        if (empty($title)) {
            $title = $this->m_video->get('title');
            if ('' != $this->m_video->get('orig_title')) {
                $title .= ' / ' . $this->m_video->get('orig_title');
            }
        }
        $link = $this->m_torrent->get('link');
        $torrent = $this->m_torrent->get('torrent');
        $size = $this->m_torrent->get('size');
        $format = $this->m_torrent->get('format');
        $translate = $this->m_torrent->get('translate');
        $quality = $this->m_torrent->get('quality');
        $video_codec = $this->m_torrent->get('video_codec');
        $video = $this->m_torrent->get('video');
        $audio_codec = $this->m_torrent->get('audio_codec');
        $audio = $this->m_torrent->get('audio');
        // Валидируем и, если нужно, изменяем
        if (false !== $this->input->post('edit')) {
            $this->load->library('validation');
            $rules = array(
            	'title'       => 'trim|required|max_length[200]',
                'link'        => 'trim|valid_url|max_length[200]',
            	'torrent'     => 'trim|required|valid_url|max_length[200]',
            	'size'        => 'trim|max_length[20]',
                'format'      => 'trim|max_length[50]',
                'translate'   => 'trim|max_length[200]',
                'quality'     => 'trim|max_length[200]',
                'video_codec' => 'trim|max_length[50]',
                'video'       => 'trim',
                'audio_codec' => 'trim|max_length[50]',
                'audio'       => 'trim'
            );
            $this->validation->set_rules($rules);
            $result = $this->validation->run();
            // Получаем из поста поля
            $title = $this->validation->title;
            $torrent = $this->validation->torrent;
            if (isset($this->validation->link)) {
                $link = $this->validation->link;
            } else {
                $link = '';
            }
            if (isset($this->validation->size)) {
                $size = $this->validation->size;
            } else {
                $size = '';
            }
            if (isset($this->validation->format)) {
                $format = $this->validation->format;
            } else {
                $format = '';
            }
            if (isset($this->validation->translate)) {
                $translate = $this->validation->translate;
            } else {
                $translate = '';
            }
            if (isset($this->validation->quality)) {
                $quality = $this->validation->quality;
            } else {
                $quality = '';
            }
            if (isset($this->validation->video_codec)) {
                $video_codec = $this->validation->video_codec;
            } else {
                $video_codec = '';
            }
            if (isset($this->validation->video)) {
                $video = $this->validation->video;
            } else {
                $video = '';
            }
            if (isset($this->validation->audio_codec)) {
                $audio_codec = $this->validation->audio_codec;
            } else {
                $audio_codec = '';
            }
            if (isset($this->validation->audio)) {
                $audio = $this->validation->audio;
            } else {
                $audio = '';
            }
            if ($result) {
                if (0 == $this->_id_torrent) {
                    $this->m_torrent->set('id_video', $this->idVideo);
                    $this->m_torrent->set('num_downloaded', 0);
                }
                // Если проверки пройдены успешно, изменяем торрент
                $this->m_torrent->set('title', $title);
                $this->m_torrent->set('torrent', preg_replace('~^' . preg_quote(base_url(), '~') . '~', '', $torrent));
                $this->m_torrent->set('link', $link);
                if (!empty($link)) {
                    $this->m_torrent->set('linkhash', md5($link));
                }
                $this->m_torrent->set('size', $size);
                $this->m_torrent->set('format', $format);
                $this->m_torrent->set('translate', $translate);
                $this->m_torrent->set('quality', $quality);
                $this->m_torrent->set('video_codec', $video_codec);
                $this->m_torrent->set('video', nl2br($video));
                $this->m_torrent->set('audio_codec', $audio_codec);
                $this->m_torrent->set('audio', nl2br($audio));
                // Сохраняем в базу
                if ($this->m_torrent->update()) {
                    if (0 == $this->_id_torrent) {
                        $this->set_message($this->lang->line('add_torrent_succ'), 'info', true);
                    } else {
                        $this->set_message($this->lang->line('edit_torrent_succ'), 'info', true);
                    }
                    $this->redirect('admin_manage_torrents', 'index', array('video' => $this->idVideo));
                }
                // Если сюда пришли, значит не все в порядке...
                if (0 == $this->_id_torrent) {
                    $this->set_message($this->lang->line('add_torrent_error'), 'error');
                } else {
                    $this->set_message($this->lang->line('edit_torrent_error'), 'error');
                }
            }
        }
        // Забиваем в дату поля
        $data['id'] = $this->_id_torrent;
        $data['title'] = htmlspecialchars($title);
        $data['link'] = htmlspecialchars($link);
        if (!preg_match('~^https?://~', $torrent)) {
            $torrent = base_url() . $torrent;
        }
        $data['torrent'] = htmlspecialchars($torrent);
        $data['size'] = $size;
        $data['format'] = $format;
        $data['translate'] = $translate;
        $data['quality'] = $quality;
        $data['video_codec'] = $video_codec;
        $data['video'] = preg_replace('~\n+~msi', "\n", str_replace('<br />', "\n", $video));
        $data['audio_codec'] = $audio_codec;
        $data['audio'] = preg_replace('~\n+~msi', "\n", str_replace('<br />', "\n", $audio));
        // Выводим
        $view = 'admin/edit_torrent.html';
        if (0 == $this->_id_torrent) {
            $view = 'admin/add_torrent.html';
        }
        $this->set_content($this->parser->parse($view, $data, true));
        $this->display();
    } // end index
    
}
